﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WcfMail.Interface;
using WcfMail;
using OpenSmtp.Mail;
using OpenPOP.POP3;

namespace Hisuntech.SystemFramework.Net.Mail
{
    public class OpenMails : Emails
    {
       

        public override bool Send(ISysMsg message)
        {
            ErrorMessage = "";
            MailMessageInfo mailInfo = (MailMessageInfo)message;
           
            try
            {
                string smtpHost = this.SMTP_Server.MailServer;
                int smtpPort = this.SMTP_Server.MailPort;
               
                string senderEmail = string.IsNullOrEmpty (mailInfo .MailFrom)?this.SMTP_Server .ServerUsername :mailInfo.MailFrom ;
                string recipientEmail = mailInfo .MailTo ;
                string subject = mailInfo.MsgSubject;
                string body = mailInfo.MsgContent;
                
                SmtpConfig.VerifyAddresses = false;

                MailMessage msg = new MailMessage(senderEmail, recipientEmail);
                msg.Charset = mailInfo.MailCharset;
                msg.Subject = subject;
                //msg.AddCustomHeader("TextPart", "0");
                //插入回执
                msg.AddCustomHeader("Disposition-Notification-To", senderEmail);
                //NOTES的回执邮件头
                msg.AddCustomHeader("ReturnReceipt", "1");

                msg.Body = body;
                msg.Priority = MailPriority.High;
                //附件处理
                if (mailInfo.AttachmentFiles != null)
                {
                    foreach (string file in mailInfo.AttachmentFiles)
                        msg.AddAttachment(file);
                }

                Smtp smtp = new Smtp(smtpHost, smtpPort);
                smtp.Username = this.SMTP_Server.ServerUsername;
                smtp.Password = this.SMTP_Server.ServerPassword;
                smtp.SendMail(msg);

                return true;
            }
            catch (MalformedAddressException mfa)
            {
                ErrorMessage = "Address error occured: " + mfa.Message;
            }
            catch (SmtpException se)
            {
                ErrorMessage = "Smtp error occured: " + se.Message;
            }
            catch (Exception e)
            {
                ErrorMessage = "Error occured: " + e.Message + "r\n" + e;
            }
            return false;

        }



        /// <summary>
        /// 接收多封邮件到邮件消息队列,如果成功，请检查message.MsgContent的值获取收到的邮件数
        /// </summary>
        /// <param name="message">邮件服务器信息</param>
        /// <param name="delMail">接收完成以后是否全部删除服务器上面的邮件</param>
        /// <param name="delMsgID">如果不全部删除，指定要删除的邮件序号（从1开始）</param>
        /// <returns>操作是否成功</returns>
        public override  bool Receive(ISysMsg message, bool delMail, int delMsgID)
        {
            this.ReceiveInit();
            bool connOk = false;
            int success = 0;
            //MailMessageInfo mailInfo = (MailMessageInfo)message;
            POPClient popClient = new POPClient();
            try
            {

                popClient.Connect(this.POP3_Server.MailServer, this.POP3_Server.MailPort, false);
                popClient.Authenticate(this.POP3_Server.ServerUsername, this.POP3_Server.ServerPassword);
                connOk = true;
                int Count = popClient.GetMessageCount();
                
                int fail = 0;
                //是否需要匹配邮件标题
                bool needMatching = !string.IsNullOrEmpty(this.MatchingTitle);
                System.Diagnostics.Debug.WriteLine("开始检查邮件");
               
                for (int i = Count; i >= 1; i -= 1)
                {
                    
                    OpenPOP.MIME.Message msg = null;
                    try
                    {
                       //记录邮件接收时间
                       DateTime mailDate;
                       OpenPOP.MIME.Header.MessageHeader msgHeader = popClient.GetMessageHeaders(i);
                       message.MsgSubject = "No." + i + ":"+msgHeader.Subject ;
                       this.Receiving(message);

                       if (DateTime.TryParse(msgHeader.Date, out mailDate))
                       {
                           System.Diagnostics.Debug.WriteLine(mailDate);
                           string mailUser = this.POP3_Server.ServerUsername;
                           
                           if (!this.IsNewMail(mailDate, mailUser, i))
                               break;
                       }
                       else
                       {
                           this.ErrorMessage = "不可识别的日期内容：" + msgHeader.Date;
                       }
                        //先判断邮件日期，在收取邮件内容
                       if (!needMatching ||
                          (needMatching && msgHeader.Subject.StartsWith(this.MatchingTitle))
                          )
                            msg = popClient.GetMessage(i);
                    }
                    catch (Exception ex)
                    {
                        ErrorMessage = ex.Message;
                    }
                  
                   
                    if (msg != null)
                    {
                        success++;
                        MailMessageInfo curinof = new MailMessageInfo();
                        curinof.MessageID = i;
                        curinof.MsgSubject = msg.Headers.Subject;
                        if (msg.MessageBody.Count > 0)
                        {
                            //string str = "以下是邮件正文：";
                            curinof.MsgContent = msg.MessageBody[msg.MessageBody.Count - 1];
                            //if (curinof.MsgContent.StartsWith(str))
                            //    curinof.MsgContent = curinof.MsgContent.Substring(str.Length);
                        }
                        curinof.MailFrom = msg.Headers.From.Address;
                        //回执标记
                        if (msg.Headers.ReplyTo != null)
                        {
                            this.ReturnReceipt.Add(curinof.MsgSubject);
                        }
                        //保存附件
                        int attFileCount = msg.Attachments.Count;
                        if (attFileCount > 0)
                        {
                            string strTime = DateTime.Now.ToString("yyyyMMddhhmmss");
                            for (int j = 0; j < attFileCount; j++)
                            {
                                if (!msg.Attachments[j].ContentFileName.Equals ("body.eml"))
                                {
                                    //必须使用原始文件名，或者程序处理起来会有问题
                                    //string fileName = base.AttachmentPath + "/" + strTime + "No" + j + "_" + msg.Attachments[j].ContentFileName;
                                    string fileName = base.AttachmentPath + "/" + msg.Attachments[j].ContentFileName;
                                    msg.Attachments[j].SaveToFile(fileName);
                                    //附件的内容，一般是base64格式; msg.Attachments[j].RawAttachment;
                                    curinof.AddAttachment(fileName);
                                }
                            }
                        }

                        this.MessageQueue.Add(curinof);
                        this.Received(curinof);
                        this.CurrentMailInfo = curinof;
                        if (this.ReceiveAndDelete)
                            popClient.DeleteMessage(i);//在这里删除邮件会导致mail.Count改变
                    }
                    else
                    {
                        fail++;
                    }
                    //删除当前邮件
                    if (i == delMsgID && delMsgID > 0 && !this.ReceiveAndDelete)
                        popClient.DeleteMessage(i);//在这里删除邮件会导致mail.Count改变
                    if (success > this.CHECK_MAIL_MAX_COUNT )
                        break;
                }
                //接收邮件完毕，删除指定的邮件
                if (delMail)
                {
                    //删除所有邮件
                    popClient.DeleteAllMessages();
                }
            }
            catch (Exception ex)
            {
                this.ErrorMessage = ex.Message;
                return false;
            }
            finally
            {
                if (connOk)
                    popClient.Disconnect();
            }
           
            System.Diagnostics.Debug.WriteLine("检查结束");
            message.MsgContent = success.ToString();
            return true;
        }

       
    }
}
